package serviceImpl;

import bean.GroudUser;
import bean.Store;
import bean.Users;
import com.nimbusds.jose.JOSEException;
import com.nimbusds.jose.KeyLengthException;
import com.qq.connect.QQConnectException;
import com.qq.connect.api.OpenID;
import com.qq.connect.api.qzone.UserInfo;
import com.qq.connect.javabeans.AccessToken;
import com.qq.connect.javabeans.qzone.UserInfoBean;
import mapper.GroudMapper;
import mapper.GroudUserMapper;
import mapper.StoreMapper;
import mapper.UsersMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import service.QqTheThirdPartyService;
import util.JwtUtil;
import util.ParameterUtils;
import util.PasswordUtil;
import util.ResponseBean;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;

@Service
public class QqTheThirdPartyServiceImpl implements QqTheThirdPartyService {

    private static Logger logger = LoggerFactory.getLogger(QqTheThirdPartyServiceImpl.class);

    @Resource
    private UsersMapper usersMapper;

    @Resource
    private StoreMapper storeMapper;

    @Resource
    private GroudUserMapper groudUserMapper;

    @Resource
    private GroudMapper groudMapper;

    @Resource
    ResponseBean responseBean;

    @Override
    public ResponseBean QqTheThirdPartyCallback(AccessToken accessToken) throws QQConnectException {

        //有3个月使用期的QQ_Token
        String token = accessToken.getAccessToken();

        //用户名对应的唯一QQID
        OpenID openID = new OpenID(token);
        String openIDString = openID.getUserOpenID();

        Users users = usersMapper.selectByQq(openIDString);

        //查询该QQ第一次登录执行以下代码
        if (users == null) {

            //获取第三方用户对象
            UserInfo qzoneUserInfo = new UserInfo(token, openIDString);
            UserInfoBean userInfoBean = qzoneUserInfo.getUserInfo();

            //获取用户名
            String username = userInfoBean.getNickname();
            //获取性别
            String sex = userInfoBean.getGender();

            //获取头像URL
            String touXiang100 = userInfoBean.getAvatar().getAvatarURL100();

            Date createTime = new Date();

            //手机号码为空
            users = new Users();
            //设置用户ID
            users.setUserId(PasswordUtil.getUUID());
            //设置用户名字
            users.setUserName(username);
            //设置用户默认密码
            users.setPassword(PasswordUtil.getSaltMD5(PasswordUtil.DEFAULT_PASSWORD));
            //设置性别
            users.setSex(sex);
            //设置头像
            users.setAvatar(touXiang100);
            //设置状态
            users.setStatus(ParameterUtils.IS_ENABLED_1);
            //设置创建时间
            users.setCreateTime(createTime);
            //设置绑定qq
            users.setQq(openIDString);
            //设置标识
            users.setIdentification(PasswordUtil.getUUID());

            //插入用户表
            usersMapper.insertSelective(users);

            //对Store对象操作 默认为买家
            Store store = new Store();
            store.setUserId(users.getUserId());

            //对Groud_User对象操作 默认为普通用户
            GroudUser groudUser = new GroudUser();
            groudUser.setUserId(users.getUserId());

            storeMapper.insertSelective(store);//除了UUID问题，其无问题
            groudUserMapper.insertSelective(groudUser);//除了UUID问题，其无问题

            //登录成功,且生成token
            try {
                String Mytoken = JwtUtil.creatToken(users.getIdentification(), ParameterUtils.USER_TYPE_5, ParameterUtils.NAV_TYPE_1);
                HashMap<String, Object> hashMap = new HashMap<>();
                hashMap.put("Token", token);
                responseBean.setAll(ResponseBean.HTTP_CODE_OK, "TokenCorrect", hashMap);
            } catch (KeyLengthException e) {
                logger.error("-----------服务器制作签名异常-----------");
                logger.error(e.getMessage());
                e.printStackTrace();
                responseBean.setAll(ResponseBean.HTTP_CODE_SYSTEM_ERROR, ResponseBean.MSG_SYSTEM_ERROR_MESSAGE, null);

            } catch (JOSEException e) {
                logger.error("-----------服务器制作签名标识异常-----------");
                logger.error(e.getMessage());
                e.printStackTrace();
                responseBean.setAll(ResponseBean.HTTP_CODE_SYSTEM_ERROR, ResponseBean.MSG_SYSTEM_ERROR_MESSAGE, null);
            }

        } else {
            //直接登录
            //登录成功,且生成token
            try {
                //获取GroudId
                String groudID = groudUserMapper.selectByGroudId(users.getUserId());
                groudID = groudMapper.selectByGroud(groudID);

                String Mytoken = JwtUtil.creatToken(users.getIdentification(), groudID, storeMapper.selectByStoreId(users.getUserId()));
                HashMap<String, Object> hashMap = new HashMap<>();
                hashMap.put("Token", token);
                responseBean.setAll(ResponseBean.HTTP_CODE_OK, "TokenCorrect", hashMap);

            } catch (KeyLengthException e) {
                logger.error("-----------服务器制作签名异常-----------");
                logger.error(e.getMessage());
                e.printStackTrace();
                responseBean.setAll(ResponseBean.HTTP_CODE_SYSTEM_ERROR, ResponseBean.MSG_SYSTEM_ERROR_MESSAGE, null);

            } catch (JOSEException e) {
                logger.error("-----------服务器制作签名标识异常-----------");
                logger.error(e.getMessage());
                e.printStackTrace();
                responseBean.setAll(ResponseBean.HTTP_CODE_SYSTEM_ERROR, ResponseBean.MSG_SYSTEM_ERROR_MESSAGE, null);
            }

        }

        return responseBean;
    }
}
